package com.zk.algorithm.stackandqueue;

import com.zk.algorithm.annotation.JianZhiOffer;
import com.zk.algorithm.annotation.LeetCode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode.com/problems/implement-stack-using-queues/discuss/62580/Accepted-clean-Java-solution
 *
 * 思路：每次 push 后，都将队列 头部 所有的元素依次重新添加进 队尾
 *
 * @author zk
 */
@JianZhiOffer
@LeetCode("225")
public class ImplementStackUsingOneQueue {

    private Queue<Integer> q = new LinkedList<Integer>();

    // Push element x onto stack.
    public void push(int x) {
        q.add(x);

        int n = q.size();
        while (n-- > 1)
            q.add(q.poll());
    }

    // Removes the element on top of the stack.
    public void pop() {
        q.poll();
    }

    // Get the top element.
    public int top() {
        return q.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }

}
